package com.zhu.storesmanager;

import java.util.List;

import com.zhu.storesmanager.models.ProjectDataItem;
import com.zhu.storesmanager.models.VisitTaskInfo;
import com.zhu.storesmanager.provider.StoresManagerSettings;
import com.zhu.storesmanager.utils.Actions;
import com.zhu.storesmanager.utils.DataUtils;
import com.zhu.storesmanager.utils.DatabaseUtil;
import com.zhu.storesmanager.utils.Log;
import com.zhu.storesmanager.utils.ViewsUtil;
import com.zhu.storesmanager.views.PopMenu;
import com.zhu.storesmanager.views.SampleModelsWallView;

import android.app.Activity;
import android.content.AsyncQueryHandler;
import android.content.ContentResolver;
import android.content.ContentValues;
import android.content.DialogInterface;
import android.content.Intent;
import android.database.Cursor;
import android.net.Uri;
import android.os.Bundle;
import android.os.Parcelable;
import android.view.KeyEvent;
import android.view.View;
import android.view.View.OnClickListener;
import android.widget.EditText;
import android.widget.RadioGroup;
import android.widget.TextView;

/**
 * 门店出样界面
 */
public class SvStoreSampleActivity extends Activity implements OnClickListener{

	//异步查询数据库token
	private final static int SAMPLE_DATA_QUERY_TOKEN = 0; //查询出样情况数据
	private final static int PROJECT_DATA_QUERY_TOKEN = 1; //拜访文本数据
	private DataQueryHandler mDataQueryHandler = null; //数据异步查询Handler

    private EditText mSampleEditText = null; //出样数输入框
    private EditText mSampleNullEditText = null; //空样数输入框
    private SampleModelsWallView mThemeSampleMoelsWallView = null; //主题形象
    private SampleModelsWallView mTimeSampleMoelsWallView = null;  //流光溢彩
    private SampleModelsWallView mOtherSampleMoelsWallView = null; //其他
    private RadioGroup mGoodRadioGroup = null; //数码演示流－好
    private RadioGroup mBadRadioGroup = null;//数码演示流－怀
    private long mDBid = -1; //数据库保存数据ID
    private VisitTaskInfo mVisitTaskInfo = null; //拜访门店数据
    private PopMenu mPopMenu = null; //弹出菜单
    private boolean isDataChange = true; //数据是否发生变化
    private List<ProjectDataItem> mProjectList = null;

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        Parcelable parcelable = getIntent().getParcelableExtra("info");
        mVisitTaskInfo = (VisitTaskInfo) parcelable;
        setContentView(R.layout.activity_sv_storesample);

        setupViews();
        initData();
    }

    /**
     * 初始化界面
     */
    private void setupViews(){
        ((TextView) findViewById(R.id.title_text)).setText(R.string.store_sample); //TITLE
        findViewById(R.id.svbottom_menu_back).setOnClickListener(this);
        findViewById(R.id.svbottom_menu_save).setOnClickListener(this);
        findViewById(R.id.svbottom_menu_menu).setOnClickListener(this);
        mSampleEditText = (EditText) findViewById(R.id.svss_samplenumber);
        mSampleNullEditText = (EditText) findViewById(R.id.svss_samplenullnumber);

        mThemeSampleMoelsWallView = (SampleModelsWallView)findViewById(R.id.svss_theme_wall);
        mThemeSampleMoelsWallView.setupViews(this, SampleModelsWallView.TYPE_THEME);
        mTimeSampleMoelsWallView = (SampleModelsWallView)findViewById(R.id.svss_time_wall);
        mTimeSampleMoelsWallView.setupViews(this, SampleModelsWallView.TYPE_TIME);
        mOtherSampleMoelsWallView = (SampleModelsWallView)findViewById(R.id.svss_other);
        mOtherSampleMoelsWallView.setupViews(this, SampleModelsWallView.TYPE_OTHER);

        View goodView = findViewById(R.id.svss_radiobutton_good);
        mGoodRadioGroup = (RadioGroup)goodView.findViewById(R.id.radiogroup);
        ((TextView)goodView.findViewById(R.id.radiogroup_label)).setText(R.string.digit_demo_good);

        View badView = findViewById(R.id.svss_radiobutton_bad);
        mBadRadioGroup = (RadioGroup)badView.findViewById(R.id.radiogroup);
        ((TextView)badView.findViewById(R.id.radiogroup_label)).setText(R.string.digit_demo_bad);
        mPopMenu = new PopMenu(this, findViewById(R.id.bottom_menu), PopMenu.MENU_SAMPLE);
        mPopMenu.setVisitTaskInfo(mVisitTaskInfo);
    }

    /**
     * (non-Javadoc)
     * @see android.view.View.OnClickListener#onClick(android.view.View)
     */
    @Override
    public void onClick(View v) {
        // TODO Auto-generated method stub
        if(v != null){
            switch(v.getId()){
                case R.id.svbottom_menu_back: //返回
                	if(!doBack()){
					    finish();
					}
                    break;
                case R.id.svbottom_menu_save: //保存
                	saveData();
                    break;
                case R.id.svbottom_menu_menu: //菜单
                	mPopMenu.showMenu();
                	break;
            }
        }
    }

    /**
     * @param requestCode 请求代码
     * @param resultCode 返回状态
     * @param data 返回数据
     * (non-Javadoc)
     * @see android.app.Activity#onActivityResult(int, int, android.content.Intent)
     */
    public void onActivityResult(int requestCode, int resultCode, Intent data){
        if(resultCode != Activity.RESULT_OK){
            return;
        }
        switch(requestCode){
            case SampleModelsWallView.TYPE_THEME:
                mThemeSampleMoelsWallView.addModel(data.getStringExtra(SvInquiryModelResultActivity.DATA));
                break;
            case SampleModelsWallView.TYPE_TIME:
                mTimeSampleMoelsWallView.addModel(data.getStringExtra(SvInquiryModelResultActivity.DATA));
                break;
            case SampleModelsWallView.TYPE_OTHER:
                mOtherSampleMoelsWallView.addModel(data.getStringExtra(SvInquiryModelResultActivity.DATA));
                break;
        }
    }

    /**
     * 初始化数据
     */
    private void initData(){
    	if(!DataUtils.mUserData.isAdmin()){ //检测非管理员
    		if(mDataQueryHandler == null){
        		mDataQueryHandler = new DataQueryHandler(getContentResolver());
        	}
    		startQueryProjects();
    	}else{
    		setDataFromAdminSearchData();
    	}
    }

    /**
     * 查询project数据
     */
    private void startQueryProjects(){
    	String where = StoresManagerSettings.DataProjectsColumns.PROJECT_TYPE + "=" + StoresManagerSettings.DataProjectsColumns.PROJECT_TYPE_SAMPLE;
    	mDataQueryHandler.startQuery(PROJECT_DATA_QUERY_TOKEN, null, 
				StoresManagerSettings.DataProjectsColumns.CONTENT_URI_NO_NOTIFICATION,
				null, where, null, null);
    }
    /**
     * 查询数据
     */
    private void startQueryDatas(){
    	String where = StoresManagerSettings.SupervisorStoreSampleColumns.STOREID + "=\'" + mVisitTaskInfo.mStoreId+ "\'";
    	mDataQueryHandler.startQuery(SAMPLE_DATA_QUERY_TOKEN, null, 
				StoresManagerSettings.SupervisorStoreSampleColumns.CONTENT_URI_NO_NOTIFICATION,
				null, where, null, null);
    }
    
    /**
     * 保存数据
     */
    private void saveData(){
    	String scountStr = mSampleEditText.getText().toString().trim(); //出样数
    	int sampleCount = 0;
    	if(scountStr != null && scountStr.length() > 0){
    		sampleCount = Integer.parseInt(mSampleEditText.getText().toString());
    	}else{
    		
    	}
    	String nonescountStr = mSampleNullEditText.getText().toString().trim(); //空出样数
    	int nonesampleCount = 0;
    	if(nonescountStr != null && nonescountStr.length() > 0){
    		nonesampleCount = Integer.parseInt(mSampleNullEditText.getText().toString());
    	}

    	int themeCount = mThemeSampleMoelsWallView.getModelCount(); //主题型号数
    	int timeCount = mTimeSampleMoelsWallView.getModelCount();   //流光
    	int otherCount = mOtherSampleMoelsWallView.getModelCount(); //其他
    	Log.d("sampleCount=" + sampleCount + "," + themeCount +"," + timeCount +"," + otherCount);
    	if(sampleCount == (themeCount + timeCount + otherCount)){ //出样 = 主题 + 流光 + 其他
    		//保存数据
    		ContentValues values = new ContentValues();
    		values.put(StoresManagerSettings.SupervisorStoreSampleColumns.SAMPLE_COUNT, sampleCount);
    		values.put(StoresManagerSettings.SupervisorStoreSampleColumns.NONESAMPLE_COUNT, nonesampleCount);
    		values.put(StoresManagerSettings.SupervisorStoreSampleColumns.THEME_MODELS, mThemeSampleMoelsWallView.getModels());
    		values.put(StoresManagerSettings.SupervisorStoreSampleColumns.TIME_MODELS, mTimeSampleMoelsWallView.getModels());
    		values.put(StoresManagerSettings.SupervisorStoreSampleColumns.TIME_SELECTED, mTimeSampleMoelsWallView.isSelected() ? 1 : 0);
    		values.put(StoresManagerSettings.SupervisorStoreSampleColumns.OTHER_MODELS, mOtherSampleMoelsWallView.getModels());
    		values.put(StoresManagerSettings.SAVED, 0);
    		//获取数据演示数据
    		int selectGoodViewID = mGoodRadioGroup.getCheckedRadioButtonId();
    		int selectBadViewID = mBadRadioGroup.getCheckedRadioButtonId();
    		if(selectGoodViewID != -1){
    			selectGoodViewID = mGoodRadioGroup.indexOfChild(mGoodRadioGroup.findViewById(selectGoodViewID));
    		}
    		if(selectBadViewID != -1){
    			selectBadViewID = mBadRadioGroup.indexOfChild(mBadRadioGroup.findViewById(selectBadViewID));
    		}
    		String demo = selectGoodViewID + DataUtils.SPLIT_ROW + selectBadViewID;
    		Log.d("DIGIT_DEMO=" + demo);
    		values.put(StoresManagerSettings.SupervisorStoreSampleColumns.DIGIT_DEMO, demo);
    		if(mDBid == -1){ //如果不存在数据 则插入新数据
    			values.put(StoresManagerSettings.SupervisorStoreSampleColumns.STOREID, mVisitTaskInfo.mStoreId);
    			Uri uri = getContentResolver().insert(StoresManagerSettings.SupervisorStoreSampleColumns.CONTENT_URI_NO_NOTIFICATION, values);
    			mDBid = Long.parseLong(uri.getPathSegments().get(1));
    		}else{ //存在则更新历史数据
    			getContentResolver().update(StoresManagerSettings.SupervisorStoreSampleColumns.getContentUri(mDBid, false), values, null, null);
    		}
    		if(!Actions.isNull(DataUtils.isProjectDataShow(mProjectList, StoresManagerSettings.DataProjectsColumns.PROJECT_TYPE_SAMPLE, 1), scountStr)
    				&& !Actions.isNull(DataUtils.isProjectDataShow(mProjectList, StoresManagerSettings.DataProjectsColumns.PROJECT_TYPE_SAMPLE, 2), nonescountStr)
    				&& checkOtherData(selectGoodViewID, selectBadViewID)
    				&& mTimeSampleMoelsWallView.checkDataCompelete(DataUtils.isProjectDataShow(mProjectList, StoresManagerSettings.DataProjectsColumns.PROJECT_TYPE_SAMPLE, 4))){
    			DatabaseUtil.saveVisitStatus(this, DatabaseUtil.TYPE_SHAPE , Integer.parseInt(mVisitTaskInfo.mVisitId), 1);
    		}else{
    			DatabaseUtil.saveVisitStatus(this, DatabaseUtil.TYPE_SHAPE , Integer.parseInt(mVisitTaskInfo.mVisitId), 0);
    		}
    		Actions.toastShort(this, this.getString(R.string.datasave_success));
    	}else{
    		Actions.toastShort(this, this.getString(R.string.input_sampleandmodelerror));
    	}
    }

    /**
     * 检测其他数据是否填写完整
     * @param goodIndex 好选中项
     * @param badIndex 坏选中项
     * @return true 数据填写完整 否则false
     */
    private boolean checkOtherData(int goodIndex, int badIndex){
    	if(DataUtils.isProjectDataShow(mProjectList, StoresManagerSettings.DataProjectsColumns.PROJECT_TYPE_SAMPLE, 6)){
    		if(goodIndex != -1 && badIndex != -1){
    			return true;
    		}else{
    			return false;
    		}
    	}
    	return true;
    }

    /**
     * 更新数据从数据库保存的数据
     * @param cursor 数据
     */
    private void updateDataFromCursor(Cursor cursor){
    	if(cursor != null && cursor.moveToFirst() && cursor.getCount() > 0){
    		boolean isSaved = cursor.getInt(cursor.getColumnIndexOrThrow(
    				StoresManagerSettings.SAVED)) == 1 ? true : false;
    		int scount = cursor.getInt(cursor.getColumnIndexOrThrow(
    				StoresManagerSettings.SupervisorStoreSampleColumns.SAMPLE_COUNT));
    		int nonescount = cursor.getInt(cursor.getColumnIndexOrThrow(
    				StoresManagerSettings.SupervisorStoreSampleColumns.NONESAMPLE_COUNT));
    		String theme = cursor.getString(cursor.getColumnIndexOrThrow(
    				StoresManagerSettings.SupervisorStoreSampleColumns.THEME_MODELS));
    		String time = cursor.getString(cursor.getColumnIndexOrThrow(
    				StoresManagerSettings.SupervisorStoreSampleColumns.TIME_MODELS));
    		String other = cursor.getString(cursor.getColumnIndexOrThrow(
    				StoresManagerSettings.SupervisorStoreSampleColumns.OTHER_MODELS));
    		String demo = cursor.getString(cursor.getColumnIndexOrThrow(
    				StoresManagerSettings.SupervisorStoreSampleColumns.DIGIT_DEMO));
    		mDBid = cursor.getLong(cursor.getColumnIndexOrThrow(
    				StoresManagerSettings.SupervisorStoreSampleColumns._ID));
    	    mSampleEditText.setText(DataUtils.updateStringDataFromHistoryData(mProjectList, "" + scount, isSaved, 
    	    		StoresManagerSettings.DataProjectsColumns.PROJECT_TYPE_SAMPLE, 1));
    		mSampleNullEditText.setText(DataUtils.updateStringDataFromHistoryData(mProjectList, "" + nonescount, isSaved, 
    				StoresManagerSettings.DataProjectsColumns.PROJECT_TYPE_SAMPLE, 2));
    		mThemeSampleMoelsWallView.addModel(DataUtils.updateStringDataFromHistoryData(mProjectList, theme, isSaved,
    				StoresManagerSettings.DataProjectsColumns.PROJECT_TYPE_SAMPLE, 3));
    		mTimeSampleMoelsWallView.addModel(DataUtils.updateStringDataFromHistoryData(mProjectList, time, isSaved,
    				StoresManagerSettings.DataProjectsColumns.PROJECT_TYPE_SAMPLE, 4));
    		mTimeSampleMoelsWallView.setSelectedStatus(cursor.getInt(cursor.getColumnIndexOrThrow(
    				StoresManagerSettings.SupervisorStoreSampleColumns.TIME_SELECTED)) == 1 ? true : false);
    		mOtherSampleMoelsWallView.addModel(DataUtils.updateStringDataFromHistoryData(mProjectList, other, isSaved,
    				StoresManagerSettings.DataProjectsColumns.PROJECT_TYPE_SAMPLE, 5));
    		demo = DataUtils.updateStringDataFromHistoryData(mProjectList, demo, isSaved,
    				StoresManagerSettings.DataProjectsColumns.PROJECT_TYPE_SAMPLE, 6);
    		int good = -1;
    		int bad = -1;
    		if(demo != null && demo.length() > 0){
    			String demos[] = demo.split(DataUtils.SPLIT_ROW);
    			good = Integer.parseInt(demos[0]);
    			bad = Integer.parseInt(demos[1]);
    		}
    		if(good != -1){
    			mGoodRadioGroup.check(mGoodRadioGroup.getChildAt(good).getId());	
    		}
    		if(bad != -1){
    			mBadRadioGroup.check(mBadRadioGroup.getChildAt(bad).getId());	
    		}
    	}
    	if(cursor != null){
    		cursor.close();
    		cursor = null;
    	}
    }

    /**
	 * 异步数据查询
	 */
	private final class DataQueryHandler extends AsyncQueryHandler {
        public DataQueryHandler(ContentResolver contentResolver) {
            super(contentResolver);
        }

        /**
         * 查询结果返回
         * (non-Javadoc)
         * @see android.content.AsyncQueryHandler#onQueryComplete(int, java.lang.Object, android.database.Cursor)
         */
        @Override
        protected void onQueryComplete(int token, Object cookie, Cursor cursor) {
            switch (token) {
                case SAMPLE_DATA_QUERY_TOKEN:
                	updateDataFromCursor(cursor);
                    break;
                case PROJECT_DATA_QUERY_TOKEN:
                	updateProjectDataFromCursor(cursor);
                	break;
                default:
                    Log.e("onQueryComplete called with unknown token " + token);
            }
        }

        @Override
        protected void onDeleteComplete(int token, Object cookie, int result) {

        }
    }

	/**
	 * 更新project数据从数据库
	 * @param cursor 数据库数据
	 */
	private void updateProjectDataFromCursor(Cursor cursor){
		mProjectList = DatabaseUtil.getProjectDataList(cursor);
		if(mProjectList != null && mProjectList.size() > 0){
			for(ProjectDataItem item : mProjectList){
				updateViewFromProject(item);
			}
		}
		startQueryDatas();
	}

	/**
	 * 从project数据更新界面
	 */
	private void updateViewFromProject(ProjectDataItem item){
	    if(item.mId == 1){
	        if(item.isShow){
	            ((TextView)findViewById(R.id.svss_samplenumber_label)).setText(item.mName);
	        }else{
	            findViewById(R.id.svss_1).setVisibility(View.GONE);
	        }
	    }else if(item.mId == 2){
	        if(item.isShow){
                ((TextView)findViewById(R.id.svss_samplenullnumber_label)).setText(item.mName);
            }else{
                findViewById(R.id.svss_2).setVisibility(View.GONE);
            }
        }else if(item.mId == 3){
            if(item.isShow){
                mThemeSampleMoelsWallView.setLabelText(item.mName);
            }else{
                mThemeSampleMoelsWallView.setVisibility(View.GONE);
            }
        }else if(item.mId == 4){
            if(item.isShow){
                mTimeSampleMoelsWallView.setLabelText(item.mName);
            }else{
                mTimeSampleMoelsWallView.setVisibility(View.GONE);
            }
        }else if(item.mId == 5){
            if(item.isShow){
                mOtherSampleMoelsWallView.setLabelText(item.mName);
            }else{
                mOtherSampleMoelsWallView.setVisibility(View.GONE);
            }
        }else if(item.mId == 6){
            if(item.isShow){
                ((TextView)findViewById(R.id.svss_digitdemo)).setText(item.mName);
            }else{
                findViewById(R.id.svss_digitdemo).setVisibility(View.GONE);
                findViewById(R.id.svss_radiobutton_good).setVisibility(View.GONE);
                findViewById(R.id.svss_radiobutton_bad).setVisibility(View.GONE);
            }
        }
	}

	/**
	 * 从管理员查询结果数据更新界面
	 */
	private void setDataFromAdminSearchData(){
		findViewById(R.id.svbottom_split_menu).setVisibility(View.GONE);
		findViewById(R.id.svbottom_menu_save).setVisibility(View.GONE);
		if(DataUtils.mQueryVisitContentResult.Data != null){
			mSampleEditText.setText(DataUtils.mQueryVisitContentResult.Data.SampleDisplayNum + "");
			mSampleEditText.setEnabled(false);
			mSampleNullEditText.setText("" + DataUtils.mQueryVisitContentResult.Data.SampleEmptyNum);
			mSampleNullEditText.setEnabled(false);
			mThemeSampleMoelsWallView.addModel(DataUtils.mQueryVisitContentResult.Data.ThemeModels);
			mThemeSampleMoelsWallView.setEnabled(false);
			mTimeSampleMoelsWallView.addModel(DataUtils.mQueryVisitContentResult.Data.OvercolorModels);
			mTimeSampleMoelsWallView.setEnabled(false);
			mOtherSampleMoelsWallView.addModel(DataUtils.mQueryVisitContentResult.Data.OtherModels);
			mOtherSampleMoelsWallView.setEnabled(false);
			int good = -1;
			int bad = -1;
			String demo = DataUtils.mQueryVisitContentResult.Data.DemoDigitalStream;
			if(demo != null && demo.length() > 0){
				String demos[] = demo.split(",");
				good = Integer.parseInt(demos[0]);
				bad = Integer.parseInt(demos[1]);
			}
			if(good >= 0 && good <=3){
				mGoodRadioGroup.check(mGoodRadioGroup.getChildAt(good).getId());	
			}
			if(bad >= 0 && bad <=3){
				mBadRadioGroup.check(mBadRadioGroup.getChildAt(bad).getId());	
			}
			ViewsUtil.setRadioGroupdisable(mGoodRadioGroup);
			ViewsUtil.setRadioGroupdisable(mBadRadioGroup);

			List<ProjectDataItem> list = DataUtils.getProjectDataList(StoresManagerSettings.DataProjectsColumns.PROJECT_TYPE_SAMPLE);
			if(list != null && list.size() > 0){
				for(ProjectDataItem item : list){
					updateViewFromProject(item);
				}
			}
		}
	}

	/**
     * 处理返回键
     */
    private boolean doBack(){
        if(isDataChange){
        	if(DataUtils.mUserData.isAdmin()){
        		return false;
        	}
            popExitDialog();
            return true;
        }
        return false;
    }

    /**
     * 按键事件处理
     */
    @Override
    public boolean onKeyDown(int keyCode, KeyEvent event) {
        if (keyCode==KeyEvent.KEYCODE_BACK) { //返回
            if(!doBack()){
               finish();
            }
            return true;
        }
        return false;
    }

    /**
     * 退出提示
     * 
     */
    private void popExitDialog() {
    	Actions.popExitDialog(this);
    }
}
